package com.feng.eduservice.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.feng.commonutils.R;
import com.feng.eduservice.entity.EduChapter;
import com.feng.eduservice.entity.EduSubject;
import com.feng.eduservice.entity.excel.SubjectData;
import com.feng.eduservice.listener.SubjecetListener;
import com.feng.eduservice.mapper.EduSubjectMapper;
import com.feng.eduservice.service.EduSubjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.feng.eduservice.util.BeanCopyUtils;
import com.feng.eduservice.vo.SubjectVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author fengge
 * @since 2023-01-15
 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {

    @Override
    public R addSubject(MultipartFile file) {
        try{
            //文件输入流
            InputStream inputStream=file.getInputStream();
            //调用方法进行读取
            EasyExcel.read(inputStream, SubjectData.class,new SubjecetListener(this)).sheet().doRead();
        }catch (Exception e){
            return R.error();
        }
        return R.ok();
    }

    @Override
    public R getAllSubject() {
        LambdaQueryWrapper<EduSubject> queryWrapper=new LambdaQueryWrapper<>();
        //所有分类
        List<EduSubject> all = this.list(null);
        //先查出一级分类
        List<EduSubject> Onesubjects = all.stream().filter(e
                -> e.getParentId().equals("0")).collect(Collectors.toList());
        //转化为vo对象
        List<SubjectVo> subjectVos = BeanCopyUtils.copyBeanList(Onesubjects, SubjectVo.class);

       //使用流为每一个一级分类设置二级分类
        subjectVos.stream().map(e-> {
            List<EduSubject> subjects = setChildren(e, all);
            List<SubjectVo> subjectVos1 = BeanCopyUtils.copyBeanList(subjects, SubjectVo.class);
           e.setChildren(subjectVos1);
           return e;
        }).collect(Collectors.toList());


      return R.ok().data("list",subjectVos);
    }



    private List<EduSubject> setChildren(SubjectVo e, List<EduSubject> all) {
        List<EduSubject> collect=all.stream().filter(b -> {
         return b.getParentId().equals(e.getId());
        }).collect(Collectors.toList());
        return collect;
    }




}
